package com.danskin.wechat.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.danskin.wechat.entity.UserInfo;
import com.danskin.wechat.model.LoginUser;
import com.danskin.wechat.service.impl.UserServiceImpl;
import com.danskin.wechat.util.CookieUtils;

public class AuthInterceptor extends HandlerInterceptorAdapter {


	
	
	@Autowired
	private UserServiceImpl userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		 String token=CookieUtils.getCookieValue(request, "SESSION_TOKEN");
//		 String token=CookieUtil.getCookie(request, "SESSION_TOKEN");
		 UserInfo user=userService.getUserByToken(token);
		 if(null==user){
			 //跳转到登录页面
			 PrintWriter out = response.getWriter();  
		        out.println("<html>");      
		        out.println("<script>");      
		        out.println("window.open ('"+request.getContextPath()+"/user/login?redirect="+request.getRequestURI()+"','_top')");      
		        out.println("</script>");      
		        out.println("</html>");
			 return false;
		 }
		 LoginUser userSession=new LoginUser();
		 userSession.setUserId(user.getId());
		 userSession.setMpId(user.getMpId());
		 userSession.setUserName(user.getUserName());
		 userSession.setIp(request.getRemoteAddr());
		 request.setAttribute("user", user);
		 request.setAttribute("loginUser", userSession);
			return true;
	}

	// 执行Handler完成执行此方法
	// 应用场景：统一异常处理，统一日志处理
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		//System.out.println("afterHandle");

	}
}
